#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

from SMTP import settings
from SMTP.Servers.ServersInterface import ServersInterface


class Sender():
    subject = None
    content = None
    nickname = None
    email = None


class Receiver():
    nickname = None
    email = None


class Smtp():
    host = None
    port = 465
    email = None
    password = None


class SmtpServer(ServersInterface):
    def send_mail(self, subject, content, receiver_email, receiver_nickname):
        """
        发送email
        :param subject:
        :param content:
        :param receiver_email:
        :param receiver_nickname:
        :return:
        """
        smtp_config: dict = settings.SMTP[settings.TARGET_SERVER]
        ret = True
        try:
            msg = MIMEText(content, 'plain', 'utf-8')
            msg['From'] = formataddr((smtp_config['nickname'], smtp_config['email']))  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
            msg['To'] = formataddr((receiver_nickname, receiver_email))  # 括号里的对应收件人邮箱昵称、收件人邮箱账号

            msg['Subject'] = subject  # 邮件的主题，也可以说是标题

            server = smtplib.SMTP_SSL(smtp_config['host'], 465)  # 发件人邮箱中的SMTP服务器，端口是25
            server.login(smtp_config['email'], smtp_config['password'])  # 括号中对应的是发件人邮箱账号、邮箱密码
            server.sendmail(smtp_config['email'], [receiver_email, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
            server.quit()  # 关闭连接
        except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
            ret = False
        return ret

    def send_email_by_smtp_setting(self, sender: Sender, receiver: Receiver, smtp: Smtp):
        """
        发送邮件
        :param sender:
        :param receiver:
        :param smtp:
        :return:
        """
        res = True
        try:
            msg = MIMEText(sender.content, 'plain', 'utf-8')
            msg['From'] = formataddr((sender.nickname, sender.email))  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
            msg['To'] = formataddr((receiver.nickname, receiver.email))  # 括号里的对应收件人邮箱昵称、收件人邮箱账号

            msg['Subject'] = sender.subject  # 邮件的主题，也可以说是标题

            server = smtplib.SMTP_SSL(smtp.host, smtp.port)  # 发件人邮箱中的SMTP服务器，端口是25
            server.login(smtp.email, smtp.password)  # 括号中对应的是发件人邮箱账号、邮箱密码
            server.sendmail(sender.email, [receiver.email, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
            server.quit()  # 关闭连接
        except Exception as e:
            res = False
            print('发送邮件错误：')
            print(str(e))
        return res
#
# if (__name__ == '__main__'):
#     manager = SmtpServer()
#     print(manager.send_mail('Test', '123', '1714255949@qq.com', 'Receiver'))
